
 /**  
 * Project Name:zhonghecrm  
 * File Name:UserRealm.java  
 * Package Name:com.crm.permision.shiro  
 * Date:2016年10月12日下午6:17:41   
 *  
*/  
  
package com.crm.permision.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.crm.model.SysRole;
import com.crm.model.SysUser;
import com.crm.service.SysRoleService;
import com.crm.service.SysUserService;
import com.crm.util.JsonUtil;
import com.crm.util.ValidateUtil;

/**  
 * ClassName:UserRealm <br/>  
 * Function: TODO ADD FUNCTION. <br/>  
 * Reason:   TODO ADD REASON. <br/>  
 * Date:     2016年10月12日 下午6:17:41 <br/>  
 * @author   hanlinxiu  
 * @version    
 * @since    JDK 1.8  
 * @see        
 */
public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		  
		String account = (String)principals.getPrimaryPrincipal();
		
		SysUser user = sysUserService.findByAccount(account);
		
		SysRole role = sysRoleService.selectByPrimaryKey(user.getRoleId());
		
		List<String> perms = new ArrayList<>();
		
		if(null != role && !ValidateUtil.isEmpty(role.getMenus()))
			perms = JsonUtil.readValue(role.getMenus(), List.class);
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		authorizationInfo.addStringPermissions(perms);
		
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		  
		String account = (String)token.getPrincipal();
		
		SysUser user = sysUserService.findByAccount(account);
		
		if(user == null){
			throw new UnknownAccountException();//没找到账号
		}
		
		if(ValidateUtil.isZero(user.getEnable())){
			throw new LockedAccountException();//账号不可用
		}
		
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("currentUser", user);
		
		return new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), ByteSource.Util.bytes(user.getUserId()), getName());
		
	}

}
  
